using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using IGlobalist.Cms.Common;
using System.IO;
using IGlobalist.Cms.Model;
using IGlobalist.Cms.Bll;
using System.Collections.Generic;

namespace IGlobalist.Cms.Admin.Control
{
    public partial class AdAddEdit : AdminBaseUserControl
    {
        public event EventHandler SaveAd;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void DoNew(object sender, EventArgs e)
        {
            NewAd();
        }

        private void NewAd()
        {
            ddlClass.Enabled = true;
            lblStatus.Text = "Add Advertise";

            ddlClass.DataBind();
            ddlClass.SelectedIndex = 0;    
            ICmsClass clazz = ClassController.GetClass(Convert.ToInt64(ddlClass.SelectedValue));
            ViewState["Ad"] = null;
            tbDescription.Text = "";
            tbName.Text = "";
            tbName.Focus();
            tbLink.Text = "";
            tbTooltip.Text = "";
            imgPhoto.Visible = false;
            tbName.Enabled = true;
            ucCmsExtPropertiesForm.PropertyList = clazz.PropertyList;
            if (ucCmsExtPropertiesForm.PropertyList.Count < 9)
                pnlExt.Visible = false;
            else 
                pnlExt.Visible = true;

            BindPages();
        }

        public void DoSave(object sender, EventArgs e)
        {
            try
            {
                bool success = false;
                long adID = 0;
                IAdContent ad = new AdContent();
                string path = Path.Combine(DataRootPhysicalPath, "Ads");
                HttpPostedFile fPost = fuFile.PostedFile;
                if (ViewState["Ad"] != null)
                {
                    ad = (IAdContent)ViewState["Ad"];
                    ad.EditedBy = IGlobalistMembership.GetUser().ID;
                    adID = ad.ID;
                }
                else
                {
                    ad.Author = IGlobalistMembership.GetUser().ID;
                    ad.Class = ClassController.GetClass(Convert.ToInt64(Session[SessionVariable.Clazz.CurrentID]));
                    ad.ClassTypeID = Convert.ToInt16(CmsObjectType.AdContent);
                    ad.ClassID = Convert.ToInt64(Session[SessionVariable.Clazz.CurrentID]);
                }

                ad.ExtPropertyList = ucCmsExtPropertiesForm.PropertyList;
                ad.Description = tbDescription.Text;
                ad.Name = tbName.Text;
                ad.Url = tbLink.Text;
                //ad.PageID = Convert.ToInt64(ddlPage.SelectedValue);

                IGlobalist.Cms.Model.PageList pagelist = new IGlobalist.Cms.Model.PageList();
                TreeNode node = tvPage.Nodes[0];
                AddPage(pagelist, node);
                ad.PageList = pagelist;

                ad.Type = (AdType)Enum.Parse(typeof(AdType), ddlType.SelectedValue);
                try
                {
                    if (fuFile.HasFile)
                        ad.Extention = Path.GetExtension(fPost.FileName);
                }
                catch
                {
                }

                if (ViewState["Ad"] != null)
                {
                    AdController.UpdateAd(ad);
                    success = true;
                }
                else
                {
                    if (IsExist(ad.Name))
                    {
                        adID = AdController.InsertAd(ad);
                        lblError.Text = "";
                        success = true;
                    }
                    else
                        lblError.Text = "Name is exist";
                }

                //upload file
                try
                {
                    if (fuFile.HasFile)
                    {
                        fPost.SaveAs(Path.Combine(path, adID + Path.GetExtension(fPost.FileName).ToString()));
                    }
                }
                catch { }



                if ((SaveAd != null) && (success == true))
                {
                    SaveAd(this, new EventArgs());
                    NewAd();
                }
            }
            catch
            {
            }
        }


        public void DoEditAd(object sender, EventArgs e)
        {
            ddlClass.Enabled = false;
            lblStatus.Text = "Edit Advertise";
            AdList al = (AdList)sender;
            long adID = Convert.ToInt64(al.SelectedID);
            IAdContent ad = new AdContent();
             ad = AdController.GetAd(adID);
             ddlClass.SelectedValue = ad.ClassID.ToString();
            ViewState["Ad"] = ad;
            ViewState["PageList"] = ad.PageList;
            BindPages();
            tbName.Text = ad.Name;
            tbLink.Text = ad.Url;
            tbTooltip.Text = ad.ToolTip;
            tbDescription.Text = ad.Description;
            imgPhoto.Visible = true;
            ddlType.SelectedValue = ((int)ad.Type).ToString();
            imgPhoto.ImageUrl = "../../ImageView.aspx?ad=" + ad.ID + ad.Extention + "" ;
            ucCmsExtPropertiesForm.PropertyList = ad.ExtPropertyList;
            if (ucCmsExtPropertiesForm.Controls.Count < 1)
                pnlExt.Visible = false;
            else
                pnlExt.Visible = true;
        }

      

        public void DoHidden(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        public void DoShow(object sender, EventArgs e)
        {
            this.Visible = true;
        }

        public bool IsExist(string name)
        {
            IList<IAdContent> listAd = AdController.GetAdList(Convert.ToInt64(Session[SessionVariable.Clazz.CurrentID]));

            foreach (IAdContent ad in listAd)
            {
                if (name == ad.Name) return false;
            }

            return true;
        }


        private void PopulateBind(IPage page, TreeNode node)
        {
            IGlobalist.Cms.Model.PageList list = new IGlobalist.Cms.Model.PageList();
         
            if (ViewState["PageList"] != null)
                list = (IGlobalist.Cms.Model.PageList)ViewState["PageList"];

            if (page.SubPageList != null)
                foreach (IPage pg in page.SubPageList)
                {
                    TreeNode subNode = new TreeNode(pg.Name, pg.ID.ToString());
                    foreach (IPage p in list)
                    {
                        if (p.ID == Convert.ToInt64(subNode.Value))
                            subNode.Checked = true;
                    }
                    node.ChildNodes.Add(subNode);
                    PopulateBind(pg, subNode);
                }

        }

        public void BindPages()
        {
            tvPage.Nodes.Clear();
            IPage root = PageController.GetPageTree();
            TreeNode nodeRoot = new TreeNode("Pages", "0");
            nodeRoot.NavigateUrl = "javascript:void(0)";
            PopulateBind(root, nodeRoot);
            tvPage.Nodes.Add(nodeRoot);
            tvPage.ExpandAll();
            tvPage.Nodes[0].ShowCheckBox = false;
            tvPage.Nodes[0].Checked = false;
        }


        protected void AddPage(IGlobalist.Cms.Model.PageList list ,  TreeNode node)
        {
            IPage page = new IGlobalist.Cms.Model.Page();
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                TreeNode nodeChild = node.ChildNodes[i];
                if (nodeChild.Checked == true)
                {
                    page = PageController.GetPage(Convert.ToInt64(nodeChild.Value));
                    list.Add(page);
                }
                AddPage(list, nodeChild);
            }

        }

        protected void ddlClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session[SessionVariable.Clazz.CurrentID] = ddlClass.SelectedValue;
            ICmsClass clazz = ClassController.GetClass(Convert.ToInt64(ddlClass.SelectedValue));
            ucCmsExtPropertiesForm.PropertyList = clazz.PropertyList;
            if (ucCmsExtPropertiesForm.PropertyList.Count > 8) fsExt.Visible = true;
            else fsExt.Visible = false;
        }

    }
}